package com.yuyou.weixin.util;

import com.github.wens.mybatisplus.plugins.Page;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by wens on 16/10/20.
 */
public class Utils {

    public static Boolean checkListNotEmpty(List list) {
        if (list == null || list.size() <= 0) {
            return false;
        } else {
            return true;
        }
    }

    public static List<Long> toLongIds(String idsStr) {

        if (StringUtils.isEmpty(idsStr)) {
            return Collections.EMPTY_LIST;
        }

        String[] idsArr = idsStr.split(",");
        if (idsArr.length == 0) {
            return Collections.emptyList();
        }
        List<Long> ids = new ArrayList<>();
        for (String c : idsArr) {
            ids.add(Long.valueOf(c.trim()));
        }
        return ids;
    }

    public static byte[] s2b(String string) {
        return string == null ? null : string.getBytes(Charset.forName("UTF8"));
    }

    public static String b2s(byte[] bytes) {
        return bytes == null ? null : new String(bytes, Charset.forName("UTF8"));
    }

    public static byte[] l2b(Long along) {
        return s2b(String.valueOf(along));
    }

    public static Long b2l(byte[] bytes) {
        String string = b2s(bytes);
        return string == null ? null : Long.parseLong(string);
    }

    public static String leftPaddingZero(Long number, int len) {
        StringBuilder sb = new StringBuilder();
        sb.append(number);
        while (sb.length() < len) {
            sb.insert(0, "0");
        }
        return sb.toString();
    }


    public static String formatDate(Date date, String pattern) {
        return new SimpleDateFormat(pattern,Locale.CHINA ).format(date);
    }


    private static String[] chineseOfWeek = {"日", "一", "二", "三", "四", "五", "六"};

    public static String formatTwoDateDefault(Date dateStart, Date dateEnd) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");


        String d1 = dateFormat.format(dateStart);
        String d2 = dateEnd == null ? "" : dateFormat.format(dateEnd);

        String t1 = timeFormat.format(dateStart);
        String t2 = dateEnd == null ? "" : timeFormat.format(dateEnd);

        StringBuilder sb = new StringBuilder(50);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateStart);

        if (d1.equals(d2)) {
            sb.append(d1).append("(周").append(chineseOfWeek[calendar.get(Calendar.DAY_OF_WEEK) - 1]).append(")").append(t1).append("-").append(t2);
        } else {
            sb.append(d1).append("(周").append(chineseOfWeek[calendar.get(Calendar.DAY_OF_WEEK) - 1]).append(")").append(t1);
            if (dateEnd != null) {
                calendar.setTime(dateEnd);
                sb.append("-").append(d2).append("(周").append(chineseOfWeek[calendar.get(Calendar.DAY_OF_WEEK) - 1]).append(")").append(t2);
            }

        }
        return sb.toString();
    }


    public static String formatFileSize(int size) {
        return size < 1024 ? String.valueOf(size) : size / 1024 < 1024 ? String.format("%dK", size / 1024) : String.format("%dM", size / 1024 / 1024);
    }

    public static int length(Object value) {
        if (value == null) {
            return 0;
        }
        if (value instanceof Collection) {
            return ((Collection) value).size();
        } else if (value.getClass().isArray()) {
            return Array.getLength(value);
        } else if (value instanceof Map) {
            return ((Map) value).size();
        } else if (value instanceof String) {
            return ((String) value).length();
        } else {
            throw new UnsupportedOperationException("Can not get length for the object : " + value);
        }
    }

    public static long percent(Long a, Long b) {

        if (a == 0 || b == 0) {
            return 0;
        }
        return (long) (100.00 * a / b);
    }

    public static String urlEncode(String srcUrl) throws UnsupportedEncodingException {
        return URLEncoder.encode(srcUrl, "utf-8");
    }

    /*public static void main(String[] args) {
        List<Long> s = new ArrayList<>();
        s.add(1L);
        s.add(2L);
        s.add(3L);
        s.add(1L);
        s = removeDuplicate(s);

        System.out.println(BigDecimals.calProportion(new BigDecimal("44"), new BigDecimal("1820.00"), new BigDecimal("2738.00")));
    }*/

    public static String camelCase(String src) {
        /*
         * 处理下划线分割命名字段
		 */
        StringBuffer sb = new StringBuffer(src.length());
        String[] fields = src.split("_");
        sb.append(fields[0].toLowerCase());
        for (int i = 1; i < fields.length; i++) {
            String temp = fields[i];
            sb.append(temp.substring(0, 1).toUpperCase());
            sb.append(temp.substring(1).toLowerCase());
        }
        return sb.toString();
    }

    final static char[] codeCharSet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

    public static String to62(long number) {
        long rest = number;
        Stack<Character> stack = new Stack<Character>();
        StringBuilder result = new StringBuilder(20);
        while (rest != 0) {
            stack.add(codeCharSet[(int) (rest - (rest / 62) * 62)]);
            rest = rest / 62;
        }
        for (; !stack.isEmpty(); ) {
            result.append(stack.pop());
        }
        return result.toString();

    }

    public static Date parseDate(String date, String format) {
        try {
            return new SimpleDateFormat(format).parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> Page<T> newPage(Page<?> page) {
        Page nPage = new Page<T>(page.getCurrent(), page.getSize());
        nPage.setTotal(page.getTotal());
        return nPage;
    }

    public static boolean isEmpty(Collection<?> c) {
        return c == null || c.isEmpty() ? true : false;
    }


    public static int parseInt(String src) {
        if (src == null) {
            src = "0";
        }
        return Integer.parseInt(src);
    }

    public static <T> List<T> unique(List<T> list) {
        return new ArrayList<>(new HashSet<T>(list));
    }

    public static String getExceptionStackTrace(Exception e) {
        ByteArrayOutputStream out = new ByteArrayOutputStream(500);
        try {
            e.printStackTrace(new PrintStream(out));
            out.flush();
        } catch (Exception ex) {
            try {
                out.write("Get exception stack trace fail".getBytes());
            } catch (IOException e1) {
                //ignore
            }
        }
        return out.toString();
    }

    public static String getPercent(String molecularString, String denominatorString, int num) {
        if (StringUtils.isEmpty(molecularString) || StringUtils.isEmpty(denominatorString) || "0".equals(molecularString) || "0".equals(denominatorString)) {
            return "0.00%";
        }

        BigDecimal molecular = new BigDecimal(molecularString);
        BigDecimal denominator = new BigDecimal(denominatorString);
        BigDecimal bigDecimal = molecular.divide(denominator, 10, BigDecimal.ROUND_HALF_UP);
        bigDecimal = BigDecimals.toFixed2(bigDecimal, num).multiply(new BigDecimal(100));
        String result = bigDecimal.toString() + "%";
        return result;
    }

    public static String formatString(Object o) {
        if (o == null) {
            return "0";
        } else {
            return o.toString();
        }
    }

    public static String formatPercentString(Object o) {
        if (o == null || "0".equals(o.toString())) {
            return "0.00%";
        } else {
            return o.toString();
        }
    }


    public static List removeDuplicate(List list) {
        List list1 = new ArrayList();
        HashSet h = new HashSet(list);
        //list.clear();
        list1.addAll(h);
        return list1;
    }

    public static Cookie findCookie(Cookie[] cookies, String cookieName){
        if(cookies == null || cookies.length == 0 ){
            return null ;
        }
        Cookie cookie = null;
        for(Cookie cookie1 : cookies){
            if(cookie1.getName().equals(cookieName)){
                cookie = cookie1;
            }
        }
        return cookie;
    }

}
